
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/*class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        list.add(root.val);
        List<Integer> leftList = preorderTraversal(root.left);
        list.addAll(leftList);

        List<Integer> rightList = preorderTraversal(root.right);
        list.addAll(rightList);

        return list;
    }
}*/


class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
/*public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        list.add(root.val);
        List<Integer> leftList = preorderTraversal(root.left);
        list.addAll(leftList);

        List<Integer> rightList = preorderTraversal(root.right);
        list.addAll(rightList);

        return list;
    }
}*/

public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        //注意这里的循环条件
        //因为后续cur为空时要弹出栈顶元素，故栈不能为空
        //且一开始时栈为空，故cur不为空就可进入循环
        //当栈空且cur为空，说明前序遍历已完成
        while (cur != null || !stack.isEmpty()) {
            //cur不为空就要进栈，并添加进顺序表
            //cur = cur.left
            while (cur != null) {
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            //当cur为空时，弹出栈顶元素（top），赋给cur其右子树
            //若cur还是为空（top.right为空），循环过来继续弹出元素，并赋给cur新的top.right
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return list;
    }
}
